package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.circle.library.CircularProgressButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.protocol.IUploadProgress;
import com.xindaoapp.happypet.protocol.PostQueue;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.KeyValuePair;


/**
 * 草稿箱
 * 
 * @author Yangqing
 * 
 */
public class GlaftActivity extends BaseActivity {

    private PullToRefreshListView vPullToRefreshListView;
    private MyPostListAdapter2 mAdapter2;
    /** 顶部发表进度条 */
    private LinearLayout vTopUnPublishContainer;

    @Override
    protected int getContentViewResId() {
        return R.layout.layout_glaft;
    }

    @Override
    protected void initViews() {
        vPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pullListview);
        vPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        vPullToRefreshListView.getRefreshableView().addHeaderView(getHeaderView(getMyPostQueue()));
        vPullToRefreshListView
                .setAdapter(mAdapter2 =
                        new MyPostListAdapter2(GlaftActivity.this, new ArrayList<Message>(),
                                Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                                R.layout.item_loading));


    }


    // class GlaftAdapter extends XinDaoBaseAdapter<PostQueue> {
    //
    // public GlaftAdapter(Context context, List<PostQueue> iniData, int pageSize, int res,
    // int loadingRes) {
    // super(context, iniData, pageSize, res, loadingRes);
    // }
    //
    // @Override
    // public View getView(int position, View convertView, ViewGroup parent, final PostQueue info) {
    // ViewHolder holder = (ViewHolder) convertView.getTag();
    // if (holder == null) {
    // holder = new ViewHolder();
    // holder.icon = (ImageView) convertView.findViewById(R.id.icon);
    // holder.plan = (TextView) convertView.findViewById(R.id.plan);
    // holder.name = (TextView) convertView.findViewById(R.id.name);
    // holder.btnUpload = (ImageView) convertView.findViewById(R.id.btn_upload);
    // holder.progressBar =
    // (CircularProgressButton) convertView.findViewById(R.id.progress);
    // holder.container = convertView.findViewById(R.id.r_top);
    // }
    //
    // if (null != info.getSendingInfo() && info.getSendingInfo().second == 0) {
    // ImageLoader.getInstance().displayImage("file://" + info.getSendingInfo().first,
    // holder.icon);
    // } else if (null != info.getSendingInfo() && info.getSendingInfo().second == 1) {
    // ImageLoader.getInstance().displayImage("file://" + info.getPostInfo().videoCover,
    // holder.icon);
    // } else if (info.getPostInfo().sendingArray.size() > 0) {
    // KeyValuePair<String, Integer> pair = info.getPostInfo().sendingArray.get(0);
    // if (pair.second == 0) {
    // ImageLoader.getInstance().displayImage("file://" + pair.first, holder.icon);
    // } else if (pair.second == 1) {
    // ImageLoader.getInstance().displayImage(
    // "file://" + info.getPostInfo().videoCover, holder.icon);
    // }
    // }
    //
    //
    // if (info.isRunning()) {// 如果是正在发帖，则添加监听器
    // info.addListener(new uploadProgress(info, holder));
    // holder.progressBar.setProgress(1);
    // resetSendState(holder, true);
    // } else {
    // resetSendState(holder, false);
    // }
    //
    // final int temp = position;
    // holder.btnUpload.setOnClickListener(new OnClickListener() {
    //
    // @Override
    // public void onClick(View v) {
    // resetSendState(holders[temp], true);
    // info.start(new uploadProgress(info, holders[temp]));
    // }
    // });
    //
    //
    // return convertView;
    // }
    //
    // }

    @Override
    protected void onLoadDatas() {
        onDataArrived(true);
        if (HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size() == 0)
            onDataArrivedEmpty();
        super.onLoadDatas();
    }

    private ViewHolder[] holders;

    /**
     * 获取需要重新提交的队列
     * 
     * @param list
     * @return
     */
    private View getHeaderView(List<PostQueue> list) {
        if (vTopUnPublishContainer == null) {
            vTopUnPublishContainer =
                    (LinearLayout) View.inflate(GlaftActivity.this, R.layout.layout_top_post, null);
        }
        vTopUnPublishContainer.removeAllViews();
        holders = new ViewHolder[list.size()];
        for (int i = 0; i < list.size(); i++) {
            final PostQueue info = list.get(i);
            final View item = View.inflate(GlaftActivity.this, R.layout.item_top_post, null);
            holders[i] = new ViewHolder();
            holders[i].icon = (ImageView) item.findViewById(R.id.icon);
            if (null != info.getSendingInfo() && info.getSendingInfo().second == 0) {
                ImageLoader.getInstance().displayImage("file://" + info.getSendingInfo().first,
                        holders[i].icon);
            } else if (null != info.getSendingInfo() && info.getSendingInfo().second == 1) {
                ImageLoader.getInstance().displayImage("file://" + info.getPostInfo().videoCover,
                        holders[i].icon);
            } else if (info.getPostInfo().sendingArray.size() > 0) {
                KeyValuePair<String, Integer> pair = info.getPostInfo().sendingArray.get(0);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holders[i].icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holders[i].icon);
                }
            }
            holders[i].plan = (TextView) item.findViewById(R.id.plan);
            holders[i].name = (TextView) item.findViewById(R.id.name);
            holders[i].btnUpload = (ImageView) item.findViewById(R.id.btn_upload);
            holders[i].progressBar = (CircularProgressButton) item.findViewById(R.id.progress);
            holders[i].container = item.findViewById(R.id.r_top);
            holders[i].name.setText(TextUtils.isEmpty(info.getPostInfo().title) ? info
                    .getPostInfo().content : info.getPostInfo().title);
            if (info.isRunning()) {// 如果是正在发帖，则添加监听器
                info.addListener(new uploadProgress(info, holders[i]));
                holders[i].progressBar.setProgress(1);
                resetSendState(holders[i], true);
            } else {
                resetSendState(holders[i], false);
            }

            final int temp = i;
            holders[i].btnUpload.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    resetSendState(holders[temp], true);
                    info.start(new uploadProgress(info, holders[temp]));
                }
            });

            holders[i].container.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    new AlertDialog.Builder(GlaftActivity.this).setTitle("删除该条帖子？")
                            .setNegativeButton("删除", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    HappyPetApplication.get().getDBManager()
                                            .deletePost(info.getPostInfo().postTime);
                                    HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                                            .remove(info);
                                    vTopUnPublishContainer.removeView(item);
                                    if (HappyPetApplication.get().getUploaQueueImpl()
                                            .getPostQueue().size() == 0) {
                                        onDataArrivedEmpty();
                                    }
                                    dialog.dismiss();
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setCancelable(true).show();

                    return false;
                }
            });

            vTopUnPublishContainer.addView(item);
        }
        return vTopUnPublishContainer;
    }


    class uploadProgress implements IUploadProgress {
        ViewHolder holder;
        PostQueue info;

        public uploadProgress(PostQueue info, ViewHolder holder) {
            super();
            this.holder = holder;
            this.info = info;
        }

        @Override
        public void success() {
            getHeaderView(getMyPostQueue());
            // onLoadDatas();
            sendBroadcast(new Intent(Constants.REFRESHPOSTINFO));
            GlaftActivity.this.finish();
        }

        @Override
        public void start(int current, int count) {
            if (count == 0) {
                holder.plan.setText(String.format("正在发送...", current, count));
            } else {
                holder.plan.setText(String.format("正在发送：%s / %s", current, count > 6 ? 6 : count));
                KeyValuePair<String, Integer> pair =
                        info.getPostInfo().sendingArray.get(current - 1);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holder.icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holder.icon);
                }
            }
        }

        @Override
        public void progress(int progress) {
            holder.progressBar.setProgress(progress);
        }

        @Override
        public void pause() {}

        @Override
        public void error(String msg) {
            holder.plan.setText("");
            resetSendState(holder, false);
        }

        @Override
        public void cancel() {}
    }

    private void resetSendState(ViewHolder holder, boolean isSending) {
        if (isSending) {
            holder.btnUpload.setEnabled(false);
            holder.btnUpload.setImageResource(R.drawable.btn_uploading);
        } else {
            holder.btnUpload.setEnabled(true);
            holder.btnUpload.setImageResource(R.drawable.btn_upload_android);
        }
    }


    /**
     * 我的发表队列
     * 
     * @return
     */
    private List<PostQueue> getMyPostQueue() {
        List<PostQueue> postQueueImpls = new ArrayList<PostQueue>();
        // 解析队列里面数据是发表还是回复
        for (int i = 0; i < HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size(); i++) {
            if (TextUtils.isEmpty(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                    .get(i).getPostInfo().tid)) {
                postQueueImpls.add(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                        .get(i));
            }
        }
        return postQueueImpls;
    }


    class ViewHolder {
        View container;
        ImageView icon;
        TextView plan;
        TextView name;
        ImageView btnUpload;
        CircularProgressButton progressBar;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        return "草稿箱";
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                GlaftActivity.this.finish();
            }
        };
    }

}
